using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Manufacturings.Infrastructrue;
using Manufacturings.Domain.Entities.Warehouses;
using Manufacturings.Infrastructrue.Error;

namespace ManufacturingsERP.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class StorageTypeController : ControllerBase
    {
        private readonly MyDbContext _context;

        public StorageTypeController(MyDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取存储类型列表
        /// </summary>
        /// <param name="pageSize">每页大小</param>
        /// <param name="page">页码</param>
        /// <param name="keyword">搜索关键词</param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<IActionResult> GetStorageTypeList(
            int pageSize = 20,
            int page = 1,
            string keyword = "")
        {
            try
            {
                var query = _context.StorageTypes.AsQueryable();

                // 搜索过滤
                if (!string.IsNullOrEmpty(keyword))
                {
                    query = query.Where(x => x.TypeName.Contains(keyword) ||
                                           (x.Description != null && x.Description.Contains(keyword)));
                }

                // 总数统计
                var totalCount = await query.CountAsync();
                var pageCount = (int)Math.Ceiling((double)totalCount / pageSize);

                // 分页查询
                var storageTypes = await query
                    .OrderBy(x => x.Id)
                    .Skip((page - 1) * pageSize)
                    .Take(pageSize)
                    .Select(x => new
                    {
                        x.Id,
                        x.TypeName,
                        x.Description,
                        x.IsEnabled,
                        x.CreateTime,
                        x.CreateUser,
                        x.ModificationTime,
                        x.ModifierName
                    })
                    .ToListAsync();

                return Ok(new APIResult<APIPageing<object>>
                {
                    Code = ResultCode.Success,
                    Message = "查询成功",
                    Data = new APIPageing<object>
                    {
                        TotalCount = totalCount,
                        PageCount = pageCount,
                        PageData = storageTypes
                    }
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new
                {
                    code = 500,
                    message = $"查询失败: {ex.Message}",
                    token = (string)null,
                    refreshToken = (string)null,
                    data = (object)null
                });
            }
        }

        /// <summary>
        /// 获取所有存储类型（不分页）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetAllStorageTypes()
        {
            try
            {
                var storageTypes = await _context.StorageTypes
                    .Where(x => x.IsEnabled)
                    .OrderBy(x => x.Id)
                    .Select(x => new
                    {
                        x.Id,
                        x.TypeName,
                        x.Description
                    })
                    .ToListAsync();

                return Ok(new
                {
                    code = 200,
                    message = "查询成功",
                    token = (string)null,
                    refreshToken = (string)null,
                    data = storageTypes
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new
                {
                    code = 500,
                    message = $"查询失败: {ex.Message}",
                    token = (string)null,
                    refreshToken = (string)null,
                    data = (object)null
                });
            }
        }
    }
}
